package servlet;

import pojo.Book;
import utils.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDAO {
    private Connection connection;

    public BookDAO() {
        try {
            connection = DBUtil.getConn();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }


    public List<Book> getAllBooks() {
        List<Book> bookList = new ArrayList<>();
        String sql = "SELECT bookID, booknum, title, author, publisherID, typeID, quantity FROM Book";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            try (ResultSet rs = statement.executeQuery()) {
                while (rs.next()) {
                    Book book = new Book(
                            rs.getInt("bookID"),
                            rs.getString("booknum"),
                            rs.getString("title"),
                            rs.getString("author"),
                            rs.getString("publisherID"),
                            rs.getString("typeID"),
                            rs.getString("quantity")
                    );
                    bookList.add(book);
                }
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
        return bookList;
    }

    public List<Book> searchBooksByTitle(String title) {
        List<Book> bookList = new ArrayList<>();
        String sql = "SELECT bookID, booknum, title, author, publisherID, typeID, quantity FROM Book WHERE title LIKE ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, "%" + title + "%");
            try (ResultSet rs = statement.executeQuery()) {
                while (rs.next()) {
                    Book book = new Book(
                            rs.getInt("bookID"),
                            rs.getString("booknum"),
                            rs.getString("title"),
                            rs.getString("author"),
                            rs.getString("publisherID"),
                            rs.getString("typeID"),
                            rs.getString("quantity")
                    );
                    bookList.add(book);
                }
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
        return bookList;
    }

    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}